<template>
    <div>{{ ip_addr }}</div>

    <div class="device-list">

    </div>

    <!-- <button type="button"></button> -->
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'

interface Action<T> {
    action: string,
    data: T
}

interface Info {
    name: string,
    description: RTCSessionDescription | null,
    candidate: RTCIceCandidate | null
}

const getBrowser = (): string => {
    var sBrowser, sUsrAg = navigator.userAgent;

    // The order matters here, and this may report false positives for unlisted browsers.

    if (sUsrAg.indexOf("Firefox") > -1) {
        sBrowser = "Mozilla Firefox";
        // "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0"
    } else if (sUsrAg.indexOf("Opera") > -1 || sUsrAg.indexOf("OPR") > -1) {
        sBrowser = "Opera";
        //"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 OPR/57.0.3098.106"
    } else if (sUsrAg.indexOf("Trident") > -1) {
        sBrowser = "Microsoft Internet Explorer";
        // "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; Zoom 3.6.0; wbx 1.0.0; rv:11.0) like Gecko"
    } else if (sUsrAg.indexOf("Edge") > -1) {
        sBrowser = "Microsoft Edge";
        // "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299"
    } else if (sUsrAg.indexOf("Chrome") > -1) {
        sBrowser = "Google Chrome or Chromium";
        // "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/66.0.3359.181 Chrome/66.0.3359.181 Safari/537.36"
    } else if (sUsrAg.indexOf("Safari") > -1) {
        sBrowser = "Apple Safari";
        // "Mozilla/5.0 (iPhone; CPU iPhone OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1 980x1306"
    } else {
        sBrowser = "unknown";
    }

    return sBrowser
}

const info: Info = reactive({
    name: getBrowser(),
    description: null,
    candidate: null
})

const ip_addr = ref('无法获取ip地址')

const rtc = new RTCPeerConnection()

const dataChannel = rtc.createDataChannel('dataChannel')

dataChannel.onopen = () => {
    console.log('打开')
}

dataChannel.onclose = () => console.log('关闭');

// 创建 WebSocket 连接.
const socket = new WebSocket('ws://192.168.10.58:8080/websocket');

socket.onopen = (event: Event) => {
    console.log('WebSocket 连接成功', event);
}

// 收到消息触发的事件
socket.onmessage = (event: MessageEvent) => {
    const deviceList = document.querySelector(".device-list");
    //   添加元素方法
    const add = (name: string) => {
        // 创建选择文件的按钮dom
        let button = document.createElement("div");
        button.setAttribute("class", "open-button");
        button.innerText = "device" + name;

        // 创建输入文件的dom节点
        let input = document.createElement("input");
        input.setAttribute("class", "input-file");
        input.setAttribute("type", "file");
        input.style.display = "none";

        // 创建一个div作为按钮和输入框的父dom节点
        let device = document.createElement("div");
        device.setAttribute("id", "device-" + name);
        device.setAttribute("class", "device");
        device.appendChild(button);
        device.appendChild(input);
        deviceList?.appendChild(device);
    };
    //   删除元素方法
    const remove = (name: string) => {
        let device = document.getElementById("device-" + name);
        if (device === null) {
            deviceList!.innerHTML = "都没有了你还在删除什么？";
            setTimeout(() => (deviceList!.innerHTML = ""), 200);
            return;
        }
        deviceList?.removeChild(device);
    };
    let result: Action<Info> & Action<Info[]> = JSON.parse(event.data)
    switch (result.action) {
        case "register": {
            add(result.data.name)
            break
        }
        case "close": {
            remove(result.data.name)
            break
        }
        case 'open': {
            result.data.forEach(device => {
                add(device.name)
            })
            break
        }
    }
    // rtc.setRemoteDescription(result.data.description!!)

    console.log('收到服务端的消息：', result.action)
}

// 发生错误触发的事件
socket.onerror = (event: Event) => {
    console.log('WebSocket 连接出错', event)
}

// 关闭连接触发的事件
socket.onclose = (event: CloseEvent) => {
    console.log('WebSocket 断开连接', event)
}


// 
rtc.onicecandidate = (event: RTCPeerConnectionIceEvent) => {
    info.candidate = event.candidate
}

rtc.createOffer()
    .then(offer => rtc.setLocalDescription(offer))
    .then(() => {
        info.description = rtc.localDescription
    })


watch(info, () => {
    if (info.description !== null && info.candidate !== null) {
        let request: Action<Info> = {
            action: 'register',
            data: info
        }
        let json = JSON.stringify(request)
        console.log(json);
        socket.send(json)
    }
})

// rtc.onicecandidate = (evt) => {
//     //监听candidate事件
//     if (evt.candidate) {
//         console.log(evt.candidate.candidate)
//         let ip_rule = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
//         var regExpExecArray = ip_rule.exec(evt.candidate.candidate)
//         if (regExpExecArray) {
//             let host = document.location.host
//             let hostname = document.location.hostname
//             let prot = host.substring(hostname.length, host.length)
//             ip_addr.value = regExpExecArray[1] + prot
//         }
//         console.log('ip_addr:', ip_addr.value) //打印获取的IP地址
//     }
// }
</script>

<style>
.device-list {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    align-items: center;
    justify-content: center;
}

.device {
    height: 10vmax;
    width: 10vmax;
    transition: all 1.3s cubic-bezier(0.65, 0.05, 0.36, 1);
    /* animation: join 1s; */
}

.open-button {
    animation: join 1s;
    height: 10vmax;
    width: 10vmax;
    border-radius: 50%;
    text-align: center;
    line-height: 10vmax;
    font-size: 2vmax;
    color: #fff;
    font-weight: 400;
    background-color: #1999ff;
    margin: 20px;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.65, 0.05, 0.36, 1);
}

.open-button:hover {
    background-color: #40a9ff;
    scale: 1.1;
}

button {
    user-select: none;
    margin: 8px;
    border: 1px solid transparent;
    border-color: #1999ff;
    background-color: #1999ff;
    color: #fff;
    border-radius: 5%;
    outline: 0;
    text-align: center;
    width: 5vmax;
    min-width: 80px;
    max-width: 200px;
    height: 5vmin;
    min-height: 30px;
    max-height: 40px;
    cursor: pointer;
    transition: background 0.3s cubic-bezier(0.65, 0.05, 0.36, 1);
}

button:hover {
    background-color: #40a9ff;
}

@keyframes join {
    from {
        opacity: 0;
        width: 0;
        height: 0;
    }

    to {
        opacity: 1;
        width: 10vmax;
        height: 10vmax;
    }
}
</style>
